//
//  StringExtension.swift
//  U17
//
//  Created by charles on 2017/10/9.
//  Copyright © 2017年 None. All rights reserved.
//

import Foundation
import UIKit
extension String {//时间戳转成字符串
    static func timeIntervalChangeToTimeStr(timeInterval:Double, _ dateFormat:String? = "yyyy-MM-dd HH:mm:ss") -> String {
        let date:Date = Date.init(timeIntervalSince1970: timeInterval)
        let formatter = DateFormatter.init()
        if dateFormat == nil {
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        }else{
            formatter.dateFormat = dateFormat
        }
        return formatter.string(from: date as Date)
    }
    //MARK:- 字符串转时间戳
        func timeStrChangeTotimeInterval(_ dateFormat:String? = "yyyy-MM-dd HH:mm:ss") -> String {
            if self.isEmpty {
                return ""
            }
            let format = DateFormatter.init()
            format.dateStyle = .medium
            format.timeStyle = .short
            if dateFormat == nil {
                format.dateFormat = "yyyy-MM-dd HH:mm:ss"
            }else{
                format.dateFormat = dateFormat
            }
            let date = format.date(from: self)
            return String(date!.timeIntervalSince1970)
    }
}
extension String {
    public func substring(from index: Int) -> String {
        if self.count > index {
            let startIndex = self.index(self.startIndex, offsetBy: index)
            let subString = self[startIndex..<self.endIndex]
            return String(subString)
        } else {
            return self
        }
    }
    
    /// 把手机号中间四位转换成星号
    func maskedPhoneNumber() -> String {
        let phoneCount = self.count
        if phoneCount < 4 {
            return self
        } else {
            let startIndex = self.index(self.startIndex, offsetBy: 3)
            let endIndex = self.index(self.startIndex, offsetBy: phoneCount - 4)
            let range = startIndex..<endIndex
            return self.replacingCharacters(in: range, with: String(repeating: "*", count: phoneCount - 7))
        }
    }
}
extension String {
     
    //将原始的url编码为合法的url
    func urlEncoded() -> String {
        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
            .urlQueryAllowed)
        return encodeUrlString ?? ""
    }
     
    //将编码后的url转换回原始的url
    func urlDecoded() -> String {
        return self.removingPercentEncoding ?? ""
    }
}
extension String {
    
    func getLabelSizet(font: UIFont, width: CGFloat) -> CGSize {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return rect.size
    }
    
    func getLabelWidth(font: UIFont, height: CGFloat = 15) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.width)
    }
    
    func getLabelHeight(font: UIFont, width: CGFloat) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.height)
    }
    
    func h_heightForLabel(font: UIFont, width: CGFloat, maxHeight: CGFloat) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.height) > maxHeight ? maxHeight : ceil(rect.height)
    }
}
extension String {
    /*
     *去掉首尾空格
     */
    var removeHeadAndTailSpace:String {
        let whitespace = NSCharacterSet.whitespaces
        return self.trimmingCharacters(in: whitespace)
    }
    /*
     *去掉首尾空格 包括后面的换行 \n
     */
    var removeHeadAndTailSpacePro:String {
        let whitespace = NSCharacterSet.whitespacesAndNewlines
        return self.trimmingCharacters(in: whitespace)
    }
    /*
     *去掉所有空格
     */
    var removeAllSapce: String {
        return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    }
    /*
     *去掉首尾空格 后 指定开头空格数
     */
    func beginSpaceNum(num: Int) -> String {
        var beginSpace = ""
        for _ in 0..<num {
            beginSpace += " "
        }
        return beginSpace + self.removeHeadAndTailSpacePro
    }
}

public extension NSMutableAttributedString {
    /// 获取范围
    func hw_allRange() -> NSRange {
        return NSMakeRange(0,length)
    }
    /// 添加中划线
    @discardableResult
    func hw_addMidline(_ lineHeght: Int) -> NSMutableAttributedString {
        addAttributes([.strikethroughStyle:lineHeght], range: hw_allRange())
        return self
    }
    /// 中划线颜色
    @discardableResult
    func hw_midlineColor(_ color: UIColor) -> NSMutableAttributedString{
        addAttributes([.strikethroughColor:color], range: hw_allRange())
        return self
    }
    /// 给文字添加描边
    ///
    /// - Parameter width: 描边宽带
    /// - Returns:
    @discardableResult
    func hw_addStroke(_ width: CGFloat) -> NSMutableAttributedString {
        addAttributes([.strokeWidth:width], range: hw_allRange())
        return self
    }
    /// 描边颜色
    @discardableResult
    func hw_strokeColor(_ color: UIColor) -> NSMutableAttributedString {
        addAttributes([.strokeColor:color], range: hw_allRange())
        return self
    }
    
    /// 添加字间距
    @discardableResult
    func hw_addSpace(_ space: CGFloat) -> NSMutableAttributedString {
        addAttributes([.kern:space], range: hw_allRange())
        return self
    }
    /// 背景色
    @discardableResult
    func hw_backgroundColor(_ color: UIColor) -> NSMutableAttributedString {
        addAttributes([.backgroundColor:color], range: hw_allRange())
        return self
    }
    /// 文字颜色
    @discardableResult
    func hw_color(_ color: UIColor) -> NSMutableAttributedString {
        addAttributes([.foregroundColor:color], range: hw_allRange())
        return self
    }

    /// 添加下划线
    @discardableResult
    func hw_addUnderLine(_ style: NSUnderlineStyle) -> NSMutableAttributedString{
        addAttributes([.underlineStyle:style.rawValue], range: hw_allRange())
        return self
    }
    /// 下划线颜色
    @discardableResult
    func hw_underLineColor(_ color: UIColor) -> NSMutableAttributedString{
        addAttributes([.underlineColor:color], range: hw_allRange())
        return self
    }
    
    /// 字体
    @discardableResult
    func hw_font(_ font: UIFont) -> NSMutableAttributedString{
        addAttributes([.font:font], range: hw_allRange())
        return self
    }
    /// 系统字体大小
    @discardableResult
    func hw_fontSize(_ size: CGFloat)->NSMutableAttributedString{
        addAttributes([.font:UIFont.systemFont(ofSize: size)], range: hw_allRange())
        return self
    }
    
    /// 添加行间距
    @discardableResult
    func hw_addLineSpace(_ space: CGFloat) -> NSMutableAttributedString {
        let style = NSMutableParagraphStyle()
        style.lineSpacing = space
        style.lineBreakMode = .byCharWrapping
        addAttribute(.paragraphStyle, value: style, range: hw_allRange())
        return self
    }
    /// 拼接富文本
    @discardableResult
    func hw_addAttribute(_ attribute: NSMutableAttributedString) -> NSMutableAttributedString {
        append(attribute)
        return self
    }
    
    /// 添加阴影
    @discardableResult
    func hw_addShadow(_ shadowOffset:CGSize? = nil ,_ color: UIColor? = nil) -> NSMutableAttributedString {
        let shadow = NSShadow.init()
        shadow.shadowColor = color == nil ? UIColor.black : color!
        shadow.shadowOffset = shadowOffset == nil ? CGSize.init(width: 2, height: 2) : shadowOffset!
        addAttributes([NSAttributedString.Key.shadow: shadow], range: hw_allRange())
        return self
    }
}


public extension String {
    /// 字符串转富文本
    func hw_toAttribute() -> NSMutableAttributedString {
        return NSMutableAttributedString(string: self)
    }
}
extension String {
    /*
     例: sortValue(by:"1.2.3".versionCompare("4"))
     */
    func versionCompare(_ otherVersion: String) -> ComparisonResult {
        // https://sarunw.com/posts/how-to-compare-two-app-version-strings-in-swift/ --> 博客地址,需要翻墙
        let versionDelimiter = "."
        
        // <1> 我们按句点 ( .)拆分版本。
        var versionComponents = self.components(separatedBy: versionDelimiter) // 通过"."拆分出 版本数字的数组 ["1", "2", "3"]
        var otherVersionComponents = otherVersion.components(separatedBy: versionDelimiter) // 通过"."拆分出 版本数字的数组 ["4"]
        
        // <2> 然后，我们找到我们将零填充的数字差异。
        let zeroDiff = versionComponents.count - otherVersionComponents.count // 因为做比较必须格式相同, 位数少的用"0"补位. 此方法为了得到需要补几个"0"
        
        // <3> 如果没有区别，我们不需要做任何事情，使用 simple .compare。
        if zeroDiff == 0 {
            // Same format, compare normally
            return self.compare(otherVersion, options: .numeric)
        } else {
            //<4> 我们填充一个缺失零的数组。
            // 根据 zeroDiff的个数,添加有几个0的数组
            let zeros = Array(repeating: "0", count: abs(zeroDiff)) // ["0", "0"]
            if zeroDiff > 0 {
                // <5> 我们将零填充数组添加到具有更少周期和零的版本中
                otherVersionComponents.append(contentsOf: zeros) // 把剩余的不足位数用"0" 补齐 ["4", "0", "0"]
            } else {
                versionComponents.append(contentsOf: zeros)
            }
            
            /*
             //<6> 我们使用数组组件从组件构建我们的版本并比较它们。这次它将具有相同的周期和位数。
             // 比较类型为 .numeric
             
             详细解析:
             1. versionDelimiter = "."
                versionComponents.joined(separator: versionDelimiter) ==> "1.2.3"
                joined ==>  数组的用法, 通过 "." 把数组中元素拼接成 字符串
             2. string.compare(...., options: .numeric)
                compare(...) ==> 字符串比较, 比较的类型为数字 .numeric
             
             caseInsensitive 不区分大小写
             literal 文字
             backwards 向后
             anchored 锚定
             numeric 数字
             
             */
            return versionComponents.joined(separator: versionDelimiter)
                .compare(otherVersionComponents.joined(separator: versionDelimiter), options: .numeric)
        }
    }
}
extension String {
    /// 字符串转拼音
    func transformToPinYin() ->String {
        let mutableString = NSMutableString(string: self)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let string = String(mutableString)
        return string.replacingOccurrences(of: " ", with: "").uppercased()
    }
    
    func isNotLetter()-> Bool {
        let upperCaseStr: String = self.uppercased()
        let c = Character(upperCaseStr)
        if  c >= "A", c <= "Z"{//
            return false
        } else {
            return true
        }
    }
}
